package com.ruoyi.flowable.service.impl;

import com.ruoyi.flowable.domain.vo.*;
import com.ruoyi.flowable.factory.FlowServiceFactory;
import com.ruoyi.flowable.service.IProcessPathAnalysisService;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProcessPathAnalysisServiceImpl extends FlowServiceFactory implements IProcessPathAnalysisService {

    /**
     * 获取流程实例的完整路径分析
     */
    @Override
    public ProcessPathAnalysisVO analyzeProcessPath(String processInstanceId) {
        ProcessPathAnalysisVO analysis = new ProcessPathAnalysisVO();

        // 1. 获取流程定义信息
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        String processDefinitionId;
        BpmnModel bpmnModel;
        String processDefinitionName;

        if (processInstance != null) {
            // 流程还在运行中
            processDefinitionId = processInstance.getProcessDefinitionId();
            bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
            processDefinitionName = getProcessDefinitionName(processDefinitionId);
        } else {
            // 流程已结束，从历史中获取信息
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            if (historicProcessInstance == null) {
                throw new RuntimeException("流程实例不存在: " + processInstanceId);
            }
            processDefinitionId = historicProcessInstance.getProcessDefinitionId();
            bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
            processDefinitionName = getProcessDefinitionName(processDefinitionId);
        }

        // 2. 获取已完成的节点
        List<CompletedNodeVO> completedNodes = getCompletedNodesVO(processInstanceId);

        // 3. 获取当前活动节点
        List<CurrentNodeVO> currentNodes = getCurrentNodesVO(processInstanceId, bpmnModel, completedNodes);

        // 4. 获取后续可能的节点路径
        List<List<FlowNodeVO>> futurePaths = getLinearFuturePaths(processInstanceId, bpmnModel,
                currentNodes, processDefinitionName, completedNodes);

        // 5. 整合成一条完整的执行链
        List<ProcessNodeVO> executionChain = buildExecutionChain(completedNodes, currentNodes, futurePaths, bpmnModel);
        analysis.setExecutionChain(executionChain);

        // 6. 获取流程定义信息
        analysis.setProcessDefinition(getProcessDefinitionVO(processDefinitionId));

        return analysis;
    }

    /**
     * 构建完整的执行链 - 只保留userTask节点
     */
    private List<ProcessNodeVO> buildExecutionChain(List<CompletedNodeVO> completedNodes,
                                                    List<CurrentNodeVO> currentNodes,
                                                    List<List<FlowNodeVO>> futurePaths,
                                                    BpmnModel bpmnModel) {
        List<ProcessNodeVO> executionChain = new ArrayList<>();

        if (currentNodes.isEmpty()) {
            return executionChain;
        }

        // 获取当前节点的ID
        String currentActivityId = currentNodes.get(0).getActivityId();

        // 1. 处理已完成节点（只保留到当前节点路径上的第一次出现的节点，去除重复）
        List<CompletedNodeVO> filteredCompletedNodes = filterCompletedNodesUnique(completedNodes, currentActivityId);
        for (CompletedNodeVO completedNode : filteredCompletedNodes) {
            // 只添加 userTask 类型的节点
            if ("userTask".equals(completedNode.getActivityType())) {
                ProcessNodeVO node = convertToProcessNodeVO(completedNode, "completed");
                executionChain.add(node);
            }
        }

        // 2. 处理当前节点
        for (CurrentNodeVO currentNode : currentNodes) {
            // 只添加 userTask 类型的节点
            if (isUserTaskType(currentNode.getType())) {
                ProcessNodeVO node = convertToProcessNodeVO(currentNode, "executing");
                executionChain.add(node);
            }
        }

        // 3. 处理未来节点（取第一条路径）
        if (!futurePaths.isEmpty() && !futurePaths.get(0).isEmpty()) {
            List<FlowNodeVO> futurePath = futurePaths.get(0);
            for (FlowNodeVO futureNode : futurePath) {
                // 跳过当前节点本身，且只添加 userTask 类型的节点
                if (!futureNode.getId().equals(currentActivityId) && "UserTask".equals(futureNode.getType())) {
                    ProcessNodeVO node = convertToProcessNodeVO(futureNode, "future");
                    executionChain.add(node);
                }
            }
        }

        return executionChain;
    }

    /**
     * 判断节点类型是否为 userTask
     */
    private boolean isUserTaskType(String activityType) {
        if (activityType == null) {
            return false;
        }
        // 处理不同类型的 userTask 表示方式
        return "userTask".equalsIgnoreCase(activityType) ||
                "UserTask".equals(activityType) ||
                activityType.toLowerCase().contains("usertask");
    }

    /**
     * 过滤已完成节点：只保留每个节点的第一次出现，直到当前节点之前
     */
    private List<CompletedNodeVO> filterCompletedNodesUnique(List<CompletedNodeVO> completedNodes, String currentActivityId) {
        List<CompletedNodeVO> filteredNodes = new ArrayList<>();
        Set<String> seenNodeIds = new HashSet<>();
        boolean reachedCurrentNode = false;

        for (CompletedNodeVO node : completedNodes) {
            // 如果遇到当前节点，停止添加
            if (node.getActivityId().equals(currentActivityId)) {
                reachedCurrentNode = true;
                continue;
            }

            // 如果已经遇到当前节点，就不再添加任何节点
            if (reachedCurrentNode) {
                continue;
            }

            // 只添加第一次出现的节点
            if (!seenNodeIds.contains(node.getActivityId())) {
                filteredNodes.add(node);
                seenNodeIds.add(node.getActivityId());
            }
        }

        return filteredNodes;
    }

    /**
     * 过滤已完成节点：只保留到当前节点第一次出现之前的部分，不包含任何后续的重复节点
     */
    private List<CompletedNodeVO> filterCompletedNodesBeforeFirstCurrent(List<CompletedNodeVO> completedNodes, String currentActivityId) {
        List<CompletedNodeVO> filteredNodes = new ArrayList<>();
        boolean foundFirstCurrentNode = false;

        for (CompletedNodeVO node : completedNodes) {
            // 如果遇到当前节点的第一次出现，就停止添加
            if (node.getActivityId().equals(currentActivityId) && !foundFirstCurrentNode) {
                foundFirstCurrentNode = true;
                // 不包含这个第一次出现的当前节点
                continue;
            }

            // 如果已经找到了第一次出现的当前节点，就不再添加任何节点
            if (foundFirstCurrentNode) {
                continue;
            }

            // 在找到第一次出现的当前节点之前，正常添加节点
            filteredNodes.add(node);
        }

        return filteredNodes;
    }

    /**
     * 转换为统一的流程节点VO
     */
    private ProcessNodeVO convertToProcessNodeVO(CompletedNodeVO completedNode, String status) {
        ProcessNodeVO node = new ProcessNodeVO();
        node.setActivityId(completedNode.getActivityId());
        node.setActivityName(completedNode.getActivityName());
        node.setActivityType(completedNode.getActivityType());
        node.setStatus(status);
        node.setStartTime(completedNode.getStartTime());
        node.setEndTime(completedNode.getEndTime());
        node.setAssignee(completedNode.getAssignee());
        node.setDuration(completedNode.getDuration());
        return node;
    }

    private ProcessNodeVO convertToProcessNodeVO(CurrentNodeVO currentNode, String status) {
        ProcessNodeVO node = new ProcessNodeVO();
        node.setActivityId(currentNode.getActivityId());
        node.setActivityName(currentNode.getActivityName());
        node.setActivityType(currentNode.getType());
        node.setStatus(status);
        node.setStartTime(currentNode.getCreateTime());
        node.setAssignee(currentNode.getAssignee());
        if ("executing".equals(status)) {
            node.setIsCurrentNode(true);
        }
        if (currentNode.getIsRejectNode() != null) {
            node.setIsRejectNode(currentNode.getIsRejectNode());
        }
        return node;
    }

    private ProcessNodeVO convertToProcessNodeVO(FlowNodeVO futureNode, String status) {
        ProcessNodeVO node = new ProcessNodeVO();
        node.setActivityId(futureNode.getId());
        node.setActivityName(futureNode.getName());
        node.setActivityType(futureNode.getType());
        node.setStatus(status);
        if (futureNode.getProperties() != null) {
            Object isReject = futureNode.getProperties().get("isReject");
            if (isReject instanceof Boolean) {
                node.setIsRejectNode((Boolean) isReject);
            }
        }
        return node;
    }

    /**
     * 获取当前活动节点（包括结束节点）
     */
    private List<CurrentNodeVO> getCurrentNodesVO(String processInstanceId, BpmnModel bpmnModel,
                                                  List<CompletedNodeVO> completedNodes) {
        // 先检查流程是否还在运行
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        List<CurrentNodeVO> currentNodes = new ArrayList<>();

        if (processInstance != null) {
            // 流程还在运行中，获取当前执行节点
            List<Execution> executions = runtimeService.createExecutionQuery()
                    .processInstanceId(processInstanceId)
                    .list()
                    .stream()
                    .filter(execution -> execution.getActivityId() != null)
                    .collect(Collectors.toList());

            for (Execution execution : executions) {
                CurrentNodeVO vo = new CurrentNodeVO();
                vo.setExecutionId(execution.getId());
                vo.setActivityId(execution.getActivityId());

                // 从 BPMN 模型中获取节点信息
                FlowElement flowElement = bpmnModel.getFlowElement(execution.getActivityId());
                if (flowElement != null) {
                    vo.setActivityName(flowElement.getName());
                    if (flowElement instanceof FlowNode) {
                        FlowNode flowNode = (FlowNode) flowElement;
                        vo.setType(flowNode.getClass().getSimpleName());
                        vo.setIsRejectNode(isRejectNode(flowNode));
                    } else {
                        // 如果是 SequenceFlow 等其他类型，设置默认类型
                        vo.setType(flowElement.getClass().getSimpleName());
                        vo.setIsRejectNode(false);
                    }
                }

                // 获取任务信息
                List<Task> tasks = taskService.createTaskQuery()
                        .executionId(execution.getId())
                        .active()
                        .list();

                if (!tasks.isEmpty()) {
                    Task task = tasks.get(0);
                    vo.setTaskId(task.getId());
                    vo.setTaskName(task.getName());
                    vo.setAssignee(task.getAssignee());
                    vo.setCreateTime(task.getCreateTime());
                }

                currentNodes.add(vo);
            }
        } else {
            // 流程已结束，从历史记录中获取最后一个节点作为当前节点
            if (!completedNodes.isEmpty()) {
                CompletedNodeVO lastNode = completedNodes.get(completedNodes.size() - 1);
                CurrentNodeVO vo = new CurrentNodeVO();
                vo.setActivityId(lastNode.getActivityId());
                vo.setActivityName(lastNode.getActivityName());
                // 使用 setType 而不是 setActivityType
                vo.setType(lastNode.getActivityType());

                // 从 BPMN 模型中获取节点类型
                FlowElement flowElement = bpmnModel.getFlowElement(lastNode.getActivityId());
                if (flowElement instanceof FlowNode) {
                    FlowNode flowNode = (FlowNode) flowElement;
                    vo.setType(flowNode.getClass().getSimpleName());

                    // 如果是结束节点，标记为当前节点
                    if (flowNode instanceof EndEvent) {
                        vo.setIsEndNode(true);
                        vo.setIsRejectNode(isRejectNode(flowNode));
                    }
                } else {
                    vo.setType(flowElement != null ? flowElement.getClass().getSimpleName() : "Unknown");
                    vo.setIsRejectNode(false);
                }

                currentNodes.add(vo);
            }
        }

        return currentNodes;
    }

    /**
     * 安全地获取 FlowNode 类型
     */
    private FlowNode getFlowNodeSafely(BpmnModel bpmnModel, String activityId) {
        FlowElement flowElement = bpmnModel.getMainProcess().getFlowElement(activityId);
        if (flowElement instanceof FlowNode) {
            return (FlowNode) flowElement;
        }
        return null;
    }

    /**
     * 获取线性后续路径（特殊处理驳回情况）
     */
    private List<List<FlowNodeVO>> getLinearFuturePaths(String processInstanceId, BpmnModel bpmnModel,
                                                        List<CurrentNodeVO> currentNodes,
                                                        String processDefinitionName,
                                                        List<CompletedNodeVO> completedNodes) {
        List<List<FlowNodeVO>> linearPaths = new ArrayList<>();

        // 获取已完成节点的ID集合
        Set<String> completedNodeIds = completedNodes.stream()
                .map(CompletedNodeVO::getActivityId)
                .collect(Collectors.toSet());

        // 获取 moveType（在驳回情况下也需要）
        String moveType = getMoveTypeFromProcess(processInstanceId);

        for (CurrentNodeVO currentNode : currentNodes) {
            String currentActivityId = currentNode.getActivityId();
            Process process = bpmnModel.getMainProcess();

            // 安全地获取 FlowElement 并检查类型
            FlowElement flowElement = process.getFlowElement(currentActivityId);
            if (flowElement instanceof FlowNode) {
                FlowNode currentFlowNode = (FlowNode) flowElement;
                List<FlowNode> linearPath = new ArrayList<>();

                // 检查当前节点是否是驳回节点
                if (currentNode.getIsRejectNode() != null && currentNode.getIsRejectNode()) {
                    // 驳回情况：回溯到导致驳回的决策网关重新探索
                    FlowNode backtrackNode = findRejectionBacktrackNode(bpmnModel, completedNodes, currentActivityId);
                    if (backtrackNode != null) {
                        // 从回溯节点开始探索，但要选择另一条路径（非驳回路径）
                        // 注意：这里传入 moveType，确保移动流程能正确选择路径
                        exploreAlternativePaths(backtrackNode, linearPath, new HashSet<>(),
                                processDefinitionName, moveType, completedNodeIds, currentActivityId);
                    } else {
                        // 如果找不到回溯节点，从流程开始重新探索
                        FlowNode startNode = findStartNode(bpmnModel);
                        if (startNode != null) {
                            exploreAlternativePaths(startNode, linearPath, new HashSet<>(),
                                    processDefinitionName, moveType, completedNodeIds, currentActivityId);
                        }
                    }
                } else {
                    // 正常情况：从当前节点开始探索
                    exploreLinearFuturePaths(currentFlowNode, linearPath, new HashSet<>(),
                            processDefinitionName, moveType, completedNodeIds);
                }

                if (!linearPath.isEmpty()) {
                    // 转换为 VO
                    List<FlowNodeVO> pathVO = linearPath.stream()
                            .map(this::convertToFlowNodeVO)
                            .collect(Collectors.toList());
                    linearPaths.add(pathVO);
                }
            } else {
                // 如果当前节点是 SequenceFlow 或其他类型，记录日志或跳过
                System.out.println("当前节点 " + currentActivityId + " 不是 FlowNode 类型，而是: " +
                        (flowElement != null ? flowElement.getClass().getSimpleName() : "null"));
            }
        }

        return linearPaths;
    }

    /**
     * 找到开始节点
     */
    private FlowNode findStartNode(BpmnModel bpmnModel) {
        Process process = bpmnModel.getMainProcess();
        for (FlowElement flowElement : process.getFlowElements()) {
            if (flowElement instanceof StartEvent) {
                return (FlowNode) flowElement;
            }
        }
        return null;
    }


    /**
     * 探索替代路径（选择非驳回路径）
     */
    private boolean exploreAlternativePaths(FlowNode currentNode, List<FlowNode> linearPath,
                                            Set<String> visited, String processDefinitionName,
                                            String moveType, Set<String> completedNodeIds,
                                            String rejectNodeId) {

        if (visited.contains(currentNode.getId())) {
            return false;
        }

        visited.add(currentNode.getId());

        // 添加到路径中（未来节点）
        linearPath.add(currentNode);

        // 检查是否是驳回节点
        if (currentNode.getId().equals(rejectNodeId) || isRejectNode(currentNode)) {
            linearPath.remove(currentNode);
            visited.remove(currentNode.getId());
            return false;
        }

        // 如果是正常的结束节点，停止探索
        if (currentNode instanceof EndEvent && !isRejectNode(currentNode)) {
            return true;
        }

        // 获取所有出口序列流
        List<SequenceFlow> outgoingFlows = currentNode.getOutgoingFlows();

        if (!outgoingFlows.isEmpty()) {
            // 特殊处理：如果是 Gateway_1ovcqqw 网关且是"移动"流程，根据 moveType 选择路径
            if ("Gateway_1ovcqqw".equals(currentNode.getId()) && "移动".equals(processDefinitionName)) {
                SequenceFlow selectedFlow = selectFlowByMoveType(outgoingFlows, moveType);
                if (selectedFlow != null && !selectedFlow.getTargetRef().equals(rejectNodeId)) {
                    FlowNode targetNode = getTargetFlowNode(selectedFlow);
                    if (targetNode != null) {
                        boolean success = exploreAlternativePaths(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds, rejectNodeId);
                        if (success) {
                            return true;
                        }
                    }
                }
                // 如果指定路径失败，尝试其他非驳回路径
                for (SequenceFlow flow : outgoingFlows) {
                    if (flow.getTargetRef().equals(rejectNodeId)) {
                        continue; // 跳过导致驳回的路径
                    }
                    if (selectedFlow != null && flow.equals(selectedFlow)) {
                        continue; // 跳过已经尝试过的路径
                    }
                    FlowNode targetNode = getTargetFlowNode(flow);
                    if (targetNode != null) {
                        boolean success = exploreAlternativePaths(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds, rejectNodeId);
                        if (success) {
                            return true;
                        }
                    }
                }
            } else if (currentNode instanceof ExclusiveGateway && "移动".equals(processDefinitionName)) {
                // 对于移动流程的其他网关，也根据条件选择路径
                SequenceFlow selectedFlow = selectFlowByConditions(outgoingFlows, moveType, rejectNodeId);
                if (selectedFlow != null) {
                    FlowNode targetNode = getTargetFlowNode(selectedFlow);
                    if (targetNode != null) {
                        boolean success = exploreAlternativePaths(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds, rejectNodeId);
                        if (success) {
                            return true;
                        }
                    }
                }
                // 如果指定路径失败，尝试其他非驳回路径
                for (SequenceFlow flow : outgoingFlows) {
                    if (flow.getTargetRef().equals(rejectNodeId)) {
                        continue; // 跳过导致驳回的路径
                    }
                    if (selectedFlow != null && flow.equals(selectedFlow)) {
                        continue; // 跳过已经尝试过的路径
                    }
                    FlowNode targetNode = getTargetFlowNode(flow);
                    if (targetNode != null) {
                        boolean success = exploreAlternativePaths(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds, rejectNodeId);
                        if (success) {
                            return true;
                        }
                    }
                }
            } else {
                // 对于其他网关或节点，遍历所有非驳回路径
                for (SequenceFlow flow : outgoingFlows) {
                    if (flow.getTargetRef().equals(rejectNodeId)) {
                        continue; // 跳过导致驳回的路径
                    }
                    FlowNode targetNode = getTargetFlowNode(flow);
                    if (targetNode != null) {
                        boolean success = exploreAlternativePaths(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds, rejectNodeId);
                        if (success) {
                            return true;
                        }
                    }
                }
            }

            linearPath.remove(currentNode);
            visited.remove(currentNode.getId());
            return false;
        }

        return true;
    }

    /**
     * 根据条件选择路径（用于移动流程的其他网关）
     */
    private SequenceFlow selectFlowByConditions(List<SequenceFlow> outgoingFlows, String moveType, String rejectNodeId) {
        for (SequenceFlow flow : outgoingFlows) {
            // 跳过驳回路径
            if (flow.getTargetRef().equals(rejectNodeId)) {
                continue;
            }

            String condition = getConditionExpression(flow);
            if (condition != null) {
                // 根据条件选择路径
                if (shouldSelectFlow(condition, moveType)) {
                    return flow;
                }
            } else {
                // 如果没有条件，选择默认路径
                return flow;
            }
        }
        return null;
    }

    /**
     * 判断是否应该选择该路径
     */
    private boolean shouldSelectFlow(String condition, String moveType) {
        if (condition == null || moveType == null) return false;

        // 清理条件字符串
        condition = condition.trim();
        if (condition.startsWith("${") && condition.endsWith("}")) {
            condition = condition.substring(2, condition.length() - 1).trim();
        }

        // 处理各种条件判断
        if (condition.contains("flag2==\"已完成\"")) {
            return "已完成".equals(moveType); // 这里需要根据实际业务逻辑调整
        }

        if (condition.contains("flag3==\"合适\"")) {
            return "合适".equals(moveType); // 这里需要根据实际业务逻辑调整
        }

        if (condition.contains("flag4==\"合规\"")) {
            return "合规".equals(moveType); // 这里需要根据实际业务逻辑调整
        }

        if (condition.contains("flag5==\"畅通\"")) {
            return "畅通".equals(moveType); // 这里需要根据实际业务逻辑调整
        }

        // 默认选择第一条路径
        return true;
    }

    /**
     * 找到导致驳回的决策网关（回溯节点）
     */
    private FlowNode findRejectionBacktrackNode(BpmnModel bpmnModel, List<CompletedNodeVO> completedNodes, String rejectNodeId) {
        // 从后往前查找，找到导致驳回的网关节点
        for (int i = completedNodes.size() - 1; i >= 0; i--) {
            CompletedNodeVO node = completedNodes.get(i);
            FlowElement flowElement = bpmnModel.getMainProcess().getFlowElement(node.getActivityId());
            if (flowElement instanceof ExclusiveGateway) {
                // 检查这个网关是否有一条路径指向驳回节点
                FlowNode gateway = (FlowNode) flowElement;
                boolean hasRejectPath = gateway.getOutgoingFlows().stream()
                        .anyMatch(flow -> flow.getTargetRef().equals(rejectNodeId));
                if (hasRejectPath) {
                    return gateway;
                }
            }
        }
        return null;
    }

    /**
     * 从回溯节点开始探索后续路径
     */
    private boolean exploreLinearFuturePathsFromBacktrack(FlowNode currentNode, List<FlowNode> linearPath,
                                                          Set<String> visited, String processDefinitionName,
                                                          String moveType, Set<String> completedNodeIds,
                                                          Set<String> rejectedPaths) {

        if (visited.contains(currentNode.getId())) {
            return false;
        }

        visited.add(currentNode.getId());
        linearPath.add(currentNode);

        if (isRejectNode(currentNode)) {
            rejectedPaths.add(currentNode.getId());
            linearPath.remove(currentNode);
            visited.remove(currentNode.getId());
            return false;
        }

        if (currentNode instanceof EndEvent && !isRejectNode(currentNode)) {
            return true;
        }

        List<SequenceFlow> outgoingFlows = currentNode.getOutgoingFlows();

        if (!outgoingFlows.isEmpty()) {
            if ("Gateway_1ovcqqw".equals(currentNode.getId()) && "移动".equals(processDefinitionName)) {
                SequenceFlow selectedFlow = selectFlowByMoveType(outgoingFlows, moveType);
                if (selectedFlow != null && !rejectedPaths.contains(selectedFlow.getTargetRef())) {
                    FlowNode targetNode = getTargetFlowNode(selectedFlow);
                    if (targetNode != null) {
                        boolean success = exploreLinearFuturePathsFromBacktrack(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds, rejectedPaths);
                        if (success) {
                            return true;
                        }
                    }
                }
                for (SequenceFlow flow : outgoingFlows) {
                    if (rejectedPaths.contains(flow.getTargetRef())) {
                        continue;
                    }
                    if (selectedFlow != null && flow.equals(selectedFlow)) {
                        continue;
                    }
                    FlowNode targetNode = getTargetFlowNode(flow);
                    if (targetNode != null) {
                        boolean success = exploreLinearFuturePathsFromBacktrack(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds, rejectedPaths);
                        if (success) {
                            return true;
                        }
                    }
                }
            } else {
                for (SequenceFlow flow : outgoingFlows) {
                    if (rejectedPaths.contains(flow.getTargetRef())) {
                        continue;
                    }
                    FlowNode targetNode = getTargetFlowNode(flow);
                    if (targetNode != null) {
                        boolean success = exploreLinearFuturePathsFromBacktrack(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds, rejectedPaths);
                        if (success) {
                            return true;
                        }
                    }
                }
            }

            linearPath.remove(currentNode);
            visited.remove(currentNode.getId());
            return false;
        }

        return true;
    }

    /**
     * 找到回溯节点（上一个userTask）
     */
    private FlowNode findBacktrackNode(BpmnModel bpmnModel, List<CompletedNodeVO> completedNodes) {
        // 从后往前查找最后一个userTask节点
        for (int i = completedNodes.size() - 1; i >= 0; i--) {
            CompletedNodeVO node = completedNodes.get(i);
            if ("userTask".equals(node.getActivityType())) {
                FlowElement flowElement = bpmnModel.getMainProcess().getFlowElement(node.getActivityId());
                if (flowElement instanceof UserTask) {
                    return (FlowNode) flowElement;
                }
            }
        }
        return null;
    }

    /**
     * 正常的路径探索（用于非驳回情况）
     */
    private boolean exploreLinearFuturePaths(FlowNode currentNode, List<FlowNode> linearPath,
                                             Set<String> visited, String processDefinitionName,
                                             String moveType, Set<String> completedNodeIds) {

        if (visited.contains(currentNode.getId())) {
            return false;
        }

        visited.add(currentNode.getId());

        // 添加到路径中（未来节点）
        linearPath.add(currentNode);

        // 检查是否是驳回节点
        if (isRejectNode(currentNode)) {
            linearPath.remove(currentNode);
            visited.remove(currentNode.getId());
            return false;
        }

        // 如果是正常的结束节点，停止探索
        if (currentNode instanceof EndEvent && !isRejectNode(currentNode)) {
            return true;
        }

        // 获取所有出口序列流
        List<SequenceFlow> outgoingFlows = currentNode.getOutgoingFlows();

        if (!outgoingFlows.isEmpty()) {
            // 特殊处理：如果是 Gateway_1ovcqqw 网关且是"移动"流程，根据 moveType 选择路径
            if ("Gateway_1ovcqqw".equals(currentNode.getId()) && "移动".equals(processDefinitionName)) {
                SequenceFlow selectedFlow = selectFlowByMoveType(outgoingFlows, moveType);
                if (selectedFlow != null) {
                    FlowNode targetNode = getTargetFlowNode(selectedFlow);
                    if (targetNode != null) {
                        boolean success = exploreLinearFuturePaths(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds);
                        if (success) {
                            return true;
                        }
                    }
                }
                // 如果指定路径失败，尝试其他路径
                for (SequenceFlow flow : outgoingFlows) {
                    if (selectedFlow != null && flow.equals(selectedFlow)) {
                        continue;
                    }
                    FlowNode targetNode = getTargetFlowNode(flow);
                    if (targetNode != null) {
                        boolean success = exploreLinearFuturePaths(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds);
                        if (success) {
                            return true;
                        }
                    }
                }
            } else {
                // 对于其他网关或节点，遍历所有路径直到找到非驳回路径
                for (SequenceFlow flow : outgoingFlows) {
                    FlowNode targetNode = getTargetFlowNode(flow);
                    if (targetNode != null) {
                        boolean success = exploreLinearFuturePaths(targetNode, linearPath, visited,
                                processDefinitionName, moveType, completedNodeIds);
                        if (success) {
                            return true;
                        }
                    }
                }
            }

            linearPath.remove(currentNode);
            visited.remove(currentNode.getId());
            return false;
        }

        return true;
    }

    /**
     * 从 SequenceFlow 获取目标 FlowNode（安全的方法）
     */
    private FlowNode getTargetFlowNode(SequenceFlow sequenceFlow) {
        if (sequenceFlow.getTargetFlowElement() instanceof FlowNode) {
            return (FlowNode) sequenceFlow.getTargetFlowElement();
        }
        return null;
    }

    /**
     * 判断节点是否是驳回节点
     */
    private boolean isRejectNode(FlowNode node) {
        if (node instanceof EndEvent) {
            // 检查节点名称是否包含"驳回"
            return node.getName() != null && node.getName().contains("驳回");
        }
        return false;
    }

    /**
     * 根据 moveType 选择正确的流程路径（仅用于移动流程的 Gateway_1ovcqqw）
     */
    private SequenceFlow selectFlowByMoveType(List<SequenceFlow> outgoingFlows, String moveType) {
        if (moveType == null) {
            return null;
        }

        for (SequenceFlow flow : outgoingFlows) {
            String condition = getConditionExpression(flow);
            if (condition != null && matchesMoveType(condition, moveType)) {
                return flow;
            }
        }

        return null;
    }

    /**
     * 获取序列流的条件表达式
     */
    private String getConditionExpression(SequenceFlow flow) {
        return flow.getConditionExpression();
    }

    /**
     * 检查条件是否匹配 moveType
     */
    private boolean matchesMoveType(String condition, String moveType) {
        if (condition == null || moveType == null) return false;

        // 清理条件字符串
        condition = condition.trim();
        if (condition.startsWith("${") && condition.endsWith("}")) {
            condition = condition.substring(2, condition.length() - 1).trim();
        }

        // 处理 moveType=="科室调整搬迁"
        if (condition.contains("moveType==\"科室调整搬迁\"") && "科室调整搬迁".equals(moveType)) {
            return true;
        }

        // 处理 moveType=="临时借用" || moveType=="永久调拨"
        if ((condition.contains("moveType==\"临时借用\"") || condition.contains("moveType==\"永久调拨\"")) &&
                ("临时借用".equals(moveType) || "永久调拨".equals(moveType))) {
            return true;
        }

        // 处理 moveType=="维修搬运"
        if (condition.contains("moveType==\"维修搬运\"") && "维修搬运".equals(moveType)) {
            return true;
        }

        return false;
    }

    /**
     * 从流程中获取 moveType - 优化简化版
     * 直接从历史变量中获取，避免运行时异常
     */
    private String getMoveTypeFromProcess(String processInstanceId) {
        try {
            // 直接从历史变量中获取 moveType
            List<HistoricVariableInstance> historicVars = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .variableName("moveType")
                    .orderByVariableName().desc() // 使用可用的排序方法
                    .list();

            if (!historicVars.isEmpty()) {
                Object value = historicVars.get(0).getValue();
                if (value != null) {
                    return value.toString();
                }
            }

            // 如果找不到 moveType，记录日志（可选）
            System.out.println("未找到流程实例 " + processInstanceId + " 的 moveType 变量");

        } catch (Exception e) {
            System.err.println("获取 moveType 失败: " + e.getMessage());
        }

        return null;
    }

    /**
     * 获取流程定义名称
     */
    private String getProcessDefinitionName(String processDefinitionId) {
        org.flowable.engine.repository.ProcessDefinition processDefinition =
                repositoryService.createProcessDefinitionQuery()
                        .processDefinitionId(processDefinitionId)
                        .singleResult();

        return processDefinition != null ? processDefinition.getName() : null;
    }

    // 其他辅助方法保持不变...
    private List<CompletedNodeVO> getCompletedNodesVO(String processInstanceId) {
        List<HistoricActivityInstance> historicActivities = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();

        return historicActivities.stream()
                .map(this::convertToCompletedNodeVO)
                .collect(Collectors.toList());
    }

    private CompletedNodeVO convertToCompletedNodeVO(HistoricActivityInstance activity) {
        CompletedNodeVO vo = new CompletedNodeVO();
        vo.setActivityId(activity.getActivityId());
        vo.setActivityName(activity.getActivityName());
        vo.setActivityType(activity.getActivityType());
        vo.setStartTime(activity.getStartTime());
        vo.setEndTime(activity.getEndTime());
        vo.setAssignee(activity.getAssignee());

        if (activity.getEndTime() != null) {
            long duration = activity.getEndTime().getTime() - activity.getStartTime().getTime();
            vo.setDurationInMillis(duration);
            vo.setDuration(formatDuration(duration));
        }

        return vo;
    }

    private FlowNodeVO convertToFlowNodeVO(FlowNode flowNode) {
        FlowNodeVO vo = new FlowNodeVO();
        vo.setId(flowNode.getId());
        vo.setName(flowNode.getName());
        vo.setType(flowNode.getClass().getSimpleName());

        Map<String, Object> properties = new HashMap<>();
        if (flowNode instanceof UserTask) {
            properties.put("assignee", ((UserTask) flowNode).getAssignee());
        } else if (flowNode instanceof ExclusiveGateway) {
            properties.put("gatewayType", "exclusive");
        } else if (flowNode instanceof EndEvent) {
            properties.put("isReject", isRejectNode(flowNode));
        }
        vo.setProperties(properties);

        return vo;
    }

    private ProcessDefinitionVO getProcessDefinitionVO(String processDefinitionId) {
        org.flowable.engine.repository.ProcessDefinition processDefinition =
                repositoryService.createProcessDefinitionQuery()
                        .processDefinitionId(processDefinitionId)
                        .singleResult();

        ProcessDefinitionVO vo = new ProcessDefinitionVO();
        if (processDefinition != null) {
            vo.setId(processDefinition.getId());
            vo.setName(processDefinition.getName());
            vo.setKey(processDefinition.getKey());
            vo.setVersion(processDefinition.getVersion());
            vo.setDeploymentId(processDefinition.getDeploymentId());
        }

        return vo;
    }

    private String formatDuration(long durationInMillis) {
        long seconds = durationInMillis / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;

        if (hours > 0) {
            return hours + "小时" + (minutes % 60) + "分钟";
        } else if (minutes > 0) {
            return minutes + "分钟" + (seconds % 60) + "秒";
        } else {
            return seconds + "秒";
        }
    }
}
